<template>
	<view class="xy-goods-sku" @touchmove.stop.prevent="">
		<view class="xy-modal-box bottom-fixed xy-modal-box-bottom share-btn-model-box ovh"  :class="[showModal?'xy-modal-show':'']" v-if="goodsInfo.sku_price">
			<view class="sku-box p-30">
				<!--text class="xyicon icon-close psa" @tap.stop="showModal = false"></text-->
				<!--商品-->
				<view class="goods-box bl-b flex p-b-30 bc-g">
					<view class="l ovh br-10">
						<image :src="currentSkuPrice.image ? currentSkuPrice.image : goodsInfo.image" mode="widthFix" />
					</view>
					<view class="r m-l-20">
						<view class="title tb lh-40 m-t-5 ovh">{{ goodsInfo.title }}</view>
						<view class="flex m-t-10">
							<view class="tb ts-40 lh-40 tc-r"><text class="ts-28">￥</text>{{ currentSkuPrice.price || goodsInfo.price }}</view>
              <view class="m-l-auto tc-999" v-if="currentSkuPrice">库存{{currentSkuPrice.stock}}件</view>
						</view>
					</view>
				</view>

				<!--规格选项 -->
				<view class="sku-item-box m-t-30">
					<view class="select-box" v-for="(item, index) in skuList" :key="item.id">
						<view class="tb">{{ item.name }}</view>
						<view class="flex m-t-20">
							<view class="item bl br-10 p-lr-40 p-tb-10 lh-28 m-r-30 ts-28" v-for="(item1, index1) in item.content" :key="item1.id"
								:class="currentSkuArray[item1.pid] == item1.id ? 'tm1b tc-w':''"
                    @tap="chooseSku(item1.pid, item1.id,item1.disabled)">
                <text :class="item1.disabled?'disable':''">{{ item1.name }}</text>
							</view>
						</view>
					</view>
          <view class="sku_checked">
            <view v-for="row in alreadyBuySku" :class="row.sku_price_id==currentSkuPrice.id?'act':''" v-if="row.goods_id==goodsInfo.id && row.buy_num>0" @tap="intTag(row.goods_sku_id_arr)">
              <text>{{row.sku_text}}</text> x {{row.buy_num}}
            </view>
          </view>
					<view class="sales m-t-50 lh-60 flex">
						<view class="tb">购买数量</view>
						<view class="r tb m-l-auto tc flex">
							<view class="ts-42 br-10" @tap="reduce">-</view>
							<input @input="buyNumInput" type="number" class="br-10 m-lr-10" :value="buyNum" />
							<view class="ts-42 br-10" @tap="add">+</view>
						</view>
					</view>
				</view>

				<!--购买按钮 -->
				<view class="btn-box tc">
					<view class="flex m-30">
            <view class="add-cart m-r-30 tc-w tm2b" @tap="confirmCart">
              加入购物车
            </view>
            <view class="buy m-l-auto tc-w tm3b" @tap="confirmBuy">
              立即购买
            </view>
					</view>
				</view>
			</view>
		</view>

		<view class="xy-modal-mask" :class="[showModal?'xy-mask-show':'']" @tap="showModal =!showModal"></view>
	</view>

</template>

<script>
// 这个组件相对于初始版本，添加了可以在单个页面渲染所有商品，可以多次在页面里面选择规格，如果之前有选择过，可以显示之前选择的数量
// 限制了 xykeep_goods_sku_price stock<=0、status='down' 的场景
// 我们可以在 两个按钮里面将我们的 confirmGoodsList 参数传出
  import { mapActions } from 'vuex';
	export default {
		components: {},
		data() {
			return {
				skuList: [],
				currentSkuPrice: '',
				currentSkuArray: [],
				buyNum: 0,
				confirmGoodsInfo: {},
        alreadyBuySku: [],
        currentSkuText: ''
			};
		},
		props: {
			goodsInfo: {},
			value: {},
      alreadyGoods: {
        type: Array,
        default(){
          return [];
        }
      },
      DefaultBuyNum: {
        type: Number,
        default(){
          return 0;
        }
      }


		},
    watch:{
      buyNum(){
        this.alreadyBuySku.forEach(row => {
          if(row.sku_price_id==this.currentSkuPrice.id){
            row.buy_num = this.buyNum;
          }
        })
      },
      currentSkuPrice(){
        var str = '';
        var currentSkuArray = this.currentSkuArray;
        currentSkuArray.forEach(v => {
          this.skuList.forEach(s => {
            s.content.forEach(u => {
              if (u.id === v) {
                str += ' ' + u.name;
              }
            });
          });
        });
        this.currentSkuText = str;
      }
    },
		created() {
      console.log(this.buyNum)
      console.log(this.DefaultBuyNum)
      this.buyNum = this.DefaultBuyNum;
			this.skuList = this.goodsInfo.sku;
			this.changeDisabled(false);
      this.alreadyBuySku = this.alreadyGoods;
      this.initSku();
		},
		mounted() {
			// 单规格选项
			if (this.goodsInfo.is_sku == 0) {
				this.currentSkuPrice = this.skuPrice[0];
			}
		},
		computed: {
			skuPrice() {
				return this.goodsInfo.sku_price;
			},

			showModal: {
				get() {
					return this.value;
				},
				set(val) {
					this.$emit('input', val);
					// return val;
				}
			},
		},

		methods: {
      ...mapActions('cart',{'addCartGoods':'addGoods'}),
			//减
			reduce(){
				this.buyNum --;
				if(this.buyNum < 0){
					this.buyNum = 0;
					this.$xyfun.msg('购买数量不能小于1');
				}
			},
			//输入
			buyNumInput(e){
				this.buyNum = e.detail.value;
				if (this.buyNum >= this.currentSkuPrice.stock) {
					this.buyNum = this.currentSkuPrice.stock;
					this.$xyfun.msg('库存不足');
					return;
				}
			},
			//加
			add(){
				this.buyNum ++;
				if (this.buyNum >= this.currentSkuPrice.stock) {
					this.buyNum = this.currentSkuPrice.stock;
					this.$xyfun.msg('库存不足');
					return;
				}
			},

      //初始化组件默认激活之前使用过的标签子类
      initSku(){
        let newPirce = this.getCanUseSkuPrice();
        if(this.alreadyBuySku.length>0){
          for (let i = 0; i < this.alreadyBuySku.length; i++) {
            if(this.goodsInfo.id==this.alreadyBuySku[i].goods_id) {
              for (let n = 0; n < newPirce.length; n++) {
                if(newPirce[n].id==this.alreadyBuySku[i].sku_price_id){
                  this.intTag(newPirce[n].goods_sku_id_arr)
                  return;
                }
              }
            }
          }
        }
      },

      //在切换标签的时候，如果确认了某一条规格数据，查找之前的记录，沿用之前记录的购买数量
      initSkuForChoose(sku){
        let Finded = false;
        for (let i = 0; i < this.alreadyBuySku.length; i++) {
          if(sku.id==this.alreadyBuySku[i].sku_price_id){

            this.buyNum = this.alreadyBuySku[i].buy_num;
            Finded = true;
          }
        }
        if(!Finded){
          this.buyNum = this.DefaultBuyNum;
        }
      },

      intTag(default_tag){
        this.currentSkuArray = [];
        for(let act_tag of default_tag){
          for(let ptags of this.skuList){
            for(let tags of ptags.content){
              if(act_tag==tags.id){
                console.log(tags)
                this.chooseSku(tags.pid,tags.id)
              }
            }
          }
        }
      },

			// 选择规格
			chooseSku(pid, skuId, disabled) {
        if(disabled) return;
				var that = this;
				var isChecked = true; // 选中 or 取消选中

				if (that.currentSkuArray[pid] != undefined && that.currentSkuArray[pid] == skuId) {//可以代表当前点击的位置是亮的情况
					// 反选
					isChecked = false;
					that.currentSkuArray.splice(pid, 1, '');
				} else {
					// 选中
					that.$set(that.currentSkuArray, pid, skuId);
				}

        // 选中的规格小类
				var chooseSkuId = [];
				that.currentSkuArray.forEach(sku => {
					if (sku != '') {
						chooseSkuId.push(sku);
					}
				});

				// 见文
				var newPrice = this.getCanUseSkuPrice();//

				// 判断所有规格大类是否选择完成
				if (chooseSkuId.length == that.skuList.length //大类长度等于现在已经选择的小类长度，是不是就当前选择标签小类的确实是有数据的
            && newPrice.length //怕没有数据,但是正常来讲都会有一条数据的
        ) {
					that.currentSkuPrice = newPrice[0];
          this.initSkuForChoose(newPrice[0]);
				} else {
					that.currentSkuPrice = '';
				}

				// 改变规格项禁用状态
				this.changeDisabled(isChecked, pid, skuId);
			},

			// 改变禁用状态
      // 这段代码非常的烧脑，我们必须举个例子才能快速的理解
      // 1.isChecked = true 正选
      // 尺码：s *m
      // 颜色：黄色 *白色
      // 类型：连衣裙 短裤（点击）
      // 只有 s码白色的短裤库存为0
      // currentSkuArray=[尺码:m]
      // 2.isChecked = false 反选
      // 尺码：s *m
      // 颜色：黄色 白色
      // 类型：连衣裙 *短裤（点击）
      // 只有 m码的黄色连衣裙库存为0
      // currentSkuArray=[尺码:m]
      //
      // currentSkuArray 代表的是 已选中的标签
			changeDisabled(isChecked = false, pid = 0, skuId = 0) {
				var newPrice = [];

				if (isChecked) {
					// 我们从仓库里面列举和短裤相关的所有款式一共2种 ,m黄色短裤、m白色短裤
					for (var price of this.skuPrice) {
						if (price.stock <= 0 || price.status=='down') {
							continue;//去除库存为0的商品规格数据
						}
						if (price.goods_sku_id_arr.indexOf(skuId.toString()) >= 0) {
							newPrice.push(price);
						}
					}
				} else {
          //获得了2条数据，只和m码相关的，m码黄色短裤，m码白色短裤
					newPrice = this.getCanUseSkuPrice();//见文
				}

				//我们把上面出现的字眼整理一下并去重
				var noChooseSkuIds = [];
				for (var price of newPrice) {
					noChooseSkuIds = noChooseSkuIds.concat(price.goods_sku_id_arr);
				}
				noChooseSkuIds = Array.from(new Set(noChooseSkuIds));
        //正选："m,黄色,白色,短裤"
        //反选："m,黄色,白色,短裤"

				if (isChecked) {
          //去除 短裤
					var index = noChooseSkuIds.indexOf(skuId.toString());
					noChooseSkuIds.splice(index, 1);
          //得到 "m,黄色,白色"
				} else {
					//去除 m
					this.currentSkuArray.forEach(sku => {
						if (sku.toString() != '') {
							var index = noChooseSkuIds.indexOf(sku.toString());
							if (index >= 0) {
								noChooseSkuIds.splice(index, 1);
							}
						}
					});
          //得到"黄色,白色,短裤"
				}

				var noCheckPtag = [];
				if (isChecked) {
          //类型那栏保持不变
          noCheckPtag = [pid];
				} else {
          //只有尺码一行不需要改变
          this.currentSkuArray.forEach((sku, key) => {
            if (sku != '') {
              noCheckPtag.push(key);
            }
          });
				}

        //遍历所有的标签父类，和所有的标签，当然只检查需要检查的部分
				for (var i in this.skuList) {//遍历3行
          //不需要检查的标签父类就跳过
					if (noCheckPtag.indexOf(this.skuList[i]['id']) >= 0) {
						continue;//正选：忽略类型那行，反选：忽略尺码哪行
					}
          //正选反选都遍历4了个标签
					for (var j in this.skuList[i]['content']) {
						if (noChooseSkuIds.indexOf(this.skuList[i]['content'][j]['id'].toString()) >= 0) {
							this.skuList[i]['content'][j]['disabled'] = false;
						} else {
							this.skuList[i]['content'][j]['disabled'] = true;
              //正选：发现 s 不在“m,黄色,白色”里面，ban掉
              //反选：发现 连衣裙 不在 "黄色,白色,短裤"里面，ban掉
						}
					}
				}
			},

			//遍历所有的商品规格数据，获取除已选中标签子类相关所有商品规格数据
      //已选中标签子类相关：店里的衣服我要黄色的和xxl的，小二你给我推荐下
			getCanUseSkuPrice() {
				var newPrice = [];

				for (var price of this.skuPrice) {
          //去除库存为0的商品规格数据
          if (price.stock <= 0 || price.status=='down') {
						continue;
					}
					var isOk = true;
          //只要和当前已选中的标签子类相关的规格数据
					this.currentSkuArray.forEach(sku => {
						if (sku.toString() != '' && price.goods_sku_id_arr.indexOf(sku.toString()) < 0) {
							isOk = false;
						}
					});

					if (isOk) {
						newPrice.push(price);
					}
				}
				return newPrice;
			},

			// 立即购买
			confirmCart() {
				if (this.confirmSku()) {
					var confirmGoodsList = this.alreadyBuySku;
          //去找前n次添加的商品规格，如果这次添加的刚好是之前有添加过的，那么就只修改之前的购买数量
          let finded = false;
          if(confirmGoodsList.length){
            for(let [index,row] of confirmGoodsList.entries()){
              if(row.sku_price_id==this.confirmGoodsInfo.sku_price_id){
                if(this.buyNum<1){
                  confirmGoodsList.splice(index,1)
                }else{
                  row.buy_num = this.buyNum;
                }
                finded = true;
              }else{
                if(row.buy_num<1){
                  confirmGoodsList.splice(index,1)
                }
              }
            }
          }
          //反之，我们就只需要添加进这条新的规格就可以了
          if(!finded){
            if(this.confirmGoodsInfo.buy_num>0){
              confirmGoodsList.push(this.confirmGoodsInfo);

            }
          }
          //直接加入项目购物车
          this.addCartGoods({
            list : confirmGoodsList,
            from: 'goods'
          }).then(res => {
            this.$xyfun.msg('加入购物车成功');
          })
          //返回到页面的方法
          // this.$emit('getSkuText', confirmGoodsList);
				}
			},

      // 立即购买
      confirmBuy() {
        if (this.confirmSku()) {
          var confirmGoodsList = [];
          confirmGoodsList.push(this.confirmGoodsInfo);
          var params = {
            goodsList: confirmGoodsList,
            from: 'buynow', //立即购买
            orderType: 'goods',
          };
          this.$Router.push({
            path: '/pages/shop/confirm',
            query: params
          });
          //返回到页面的方法
          // this.$emit('getSkuText', confirmGoodsList);
        }
      },

			// 确认前检查并获取数据
			confirmSku() {
        if(!this.currentSkuPrice){
          this.$xyfun.msg('请完善规格信息');
          return false;
        }
        // if(!this.buyNum){
        //   this.$xyfun.msg('请选择数量');
        //   return false;
        // }
				if (this.currentSkuPrice.stock == 0 || this.currentSkuPrice.stock < this.goodsNum) {
					this.$xyfun.msg('库存不足');
					// this.showModal = false;
					return false;
				} else {
					this.currentSkuPrice.buy_num = this.buyNum;
					this.confirmGoodsInfo = {
						goods_id: this.currentSkuPrice.goods_id,
						buy_num: this.currentSkuPrice.buy_num,
						sku_price_id: this.currentSkuPrice.id,
						goods_price: this.currentSkuPrice.price,
            sku_text : this.currentSkuText,
            goods_sku_id_arr : this.currentSkuPrice.goods_sku_id_arr
					};
					if (!this.confirmGoodsInfo.sku_price_id) {
						this.$xyfun.msg('请选择规格');
						return false;
					} else {
						this.showModal = false;
						return true;
					}
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.sku-box{
		.icon-close{right: 30rpx;top: 20rpx;}

		.goods-box{
			.l{
				width: 150rpx;height: 150rpx;
				image{width: 150rpx;}
			}
			.r{
				.title{height: 80rpx;}
				width: 520rpx;
			}
		}
		.sales{
			.r view{height: 60rpx;width: 60rpx;}
			.r input{width: 100rpx;height: 60rpx;}
		}

		.btn-box{
			.buy,.add-cart{width: 280rpx;height: 76rpx;border-radius: 36rpx;line-height: 72rpx;}
		}
	}

  .sku_checked{
    display: flex;
    flex-wrap: wrap;
    margin-top: 50rpx;
    view{
      margin-right: 30rpx;
      font-size: 22rpx;
      color: #6c6c6c;
      text{
        margin-right: 8rpx;
        background: #c7c7c7;
        color: #fff;
        padding: 4rpx 20rpx;
        border-radius: 20rpx;
      }
    }
    .act{
      text{
        background: $theme1;
      }
    }
  }
  .disable{
    text-decoration: line-through;
  }
</style>
